package com.sh.controller;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sh.tcp.ClientChannelMap;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
* @comments
* @author  zg
* @date 2018年4月6日
*/
@RestController
@RequestMapping("/push")
public class PushConntroller {
	private Logger logger = LogManager.getLogger(this.getClass());
	
	/**
	 * 硬件设备的绑定请求
	 * @author zg
	 * @date 2018年4月5日
	 * @return
	 */
	@RequestMapping("/msg")
	public String msg(String clientId, String content) {
		logger.info("Push msg, clientId={}, content={}", clientId, content);
		
		if(StringUtils.isBlank(clientId) || StringUtils.isBlank(content)) {
			return "fail:请求参数不能为空";
		}

		//Channel channel = ClientChannelMap.get(clientId);
		ChannelHandlerContext channel = ClientChannelMap.get(clientId);
		if(channel == null) {
			return "fail:客户端信息不存在";
		}
		try {
			byte[] contentBytes = content.getBytes("UTF-8");
			ByteBuf buf = channel.alloc().buffer(); 
			buf.writeBytes(contentBytes); 
			channel.writeAndFlush(buf);
		} catch (Exception e) {
			logger.error("", e);
		}
		
		return "done!";
	}

}
